<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/11/14 10:24
 * Desc: 抽象退款规则
 */
abstract class Contract_Refund_Rule
{
    /**
     * 退款规则名称
     */
    const REFUND_RESTRICTION_NAME = [
        0 => '无条件退',
        1 => '不可退改',
        2 => '有条件退',
    ];

    /**
     * 获取格式化后的退款规则
     * @param $suit_id
     * @param string $product_id
     * @return array
     */
    abstract function get_format_refund_rule($suit_id, string $product_id = ''): array;

    /**
     * 获取退款规则
     * @param $suit_id
     * @param string $product_id
     * @return array
     */
    abstract function get_refund_rule($suit_id, string $product_id = ''): array;

    /**
     * 获取退款手续费
     * @param $order_id
     * @param $pay_price
     * @param array $params 'usedate'
     * @return float
     * @throws Exception
     */
    public function get_refund_cost($order_id, $pay_price, $params = []): float
    {
        $refund_rule = DB::select('rule')
            ->from('member_order_refund_rule')
            ->where('order_id', '=', $order_id)
            ->execute()
            ->current();
        if (!empty($refund_rule['rule'])) {
            $rules             = unserialize($refund_rule['rule']);
            $now_time          = time(); // 当前时间
            $order_refund_rule = ''; // 订单当前退款规则

            // 计算退款手续费
            foreach ($rules as $rule) {
                $use_date    = new DateTime($params['usedate']);
                $before_day  = $rule['before_day'];
                $before_date = $rule['before_date'] != '00:00' ? $rule['before_date'] : '23:59:59';

                // 计算提前日期相对于use_date的日期
                $use_date->modify('-' . $before_day . 'day');
                $new_date    = $use_date->format('Y-m-d');
                $before_time = strtotime($new_date . ' ' . $before_date);
                if ($before_time >= $now_time) {
                    $order_refund_rule = $rule;
                    break;
                }
            }

            if (!empty($order_refund_rule)) {
                // fee_type = 1 为百分比，fee_type = 2 为固定金额
                if ($order_refund_rule['fee_type'] == 1) {
                    $percent = bcdiv($order_refund_rule['fee'], 100, 4);
                    return bcmul($percent, $pay_price, 2);
                } else {
                    return min($order_refund_rule['fee'], $pay_price);
                }
            } else {
                // 如果没有满足的退款规则，支付金额全扣
                return $pay_price;
            }
        }

        // 未配置退款规则，不收取手续费
        return 0;
    }

    /**
     * 获取退款规则名称
     * @param int $refund_restriction 退款规则
     * @return string
     */
    public function get_refund_restriction_name($refund_restriction): string
    {
        $arr = self::REFUND_RESTRICTION_NAME;
        return $arr[$refund_restriction] ?: '';
    }
}